package com.example.management.system.controller

import com.example.management.common.annotation.Log
import com.example.management.common.config.Constant
import com.example.management.common.controller.BaseController
import com.example.management.common.domain.Tree
import com.example.management.common.service.DictService
import com.example.management.common.utils.MD5Utils
import com.example.management.common.utils.PageUtils
import com.example.management.common.utils.Query
import com.example.management.common.utils.R
import com.example.management.system.domain.DeptDO
import com.example.management.system.domain.UserDO
import com.example.management.system.service.RoleService
import com.example.management.system.service.UserService
import com.example.management.system.vo.UserVO
import org.apache.shiro.authz.annotation.RequiresPermissions
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import springfox.documentation.annotations.ApiIgnore
import java.util.HashMap
import javax.servlet.http.HttpServletRequest

@ApiIgnore
@RequestMapping("/sys/user")
@Controller
class UserController : BaseController() {
    private val prefix = "system/user"
    @Autowired
    internal var userService: UserService? = null
    @Autowired
    internal var roleService: RoleService? = null
    @Autowired
    internal var dictService: DictService? = null

    @RequiresPermissions("sys:user:user")
    @GetMapping("")
    internal fun user(model: Model): String {
        return "$prefix/user"
    }

    @GetMapping("/list")
    @ResponseBody
    internal fun list(@RequestParam params: Map<String, Any>): PageUtils {
        // 查询列表数据
        val query = Query(params)
        val sysUserList = userService!!.list(query)
        val total = userService!!.count(query)
        return PageUtils(sysUserList, total)
    }

    @RequiresPermissions("sys:user:add")
    @Log("添加用户")
    @GetMapping("/add")
    internal fun add(model: Model): String {
        val roles = roleService!!.list()
        model.addAttribute("roles", roles)
        return "$prefix/add"
    }

    @RequiresPermissions("sys:user:edit")
    @Log("编辑用户")
    @GetMapping("/edit/{id}")
    internal fun edit(model: Model, @PathVariable("id") id: Long?): String {
        val userDO = userService!!.get(id)
        model.addAttribute("user", userDO)
        val roles = roleService!!.list(id)
        model.addAttribute("roles", roles)
        return "$prefix/edit"
    }

    @RequiresPermissions("sys:user:add")
    @Log("保存用户")
    @PostMapping("/save")
    @ResponseBody
    internal fun save(user: UserDO): R {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序")
        }
        user.password =(MD5Utils.encrypt(user.username!!, user.password!!))
        return if (userService!!.save(user) > 0) {
            R.ok()
        } else R.error()
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/update")
    @ResponseBody
    internal fun update(user: UserDO): R {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序")
        }
        return if (userService!!.update(user) > 0) {
            R.ok()
        } else R.error()
    }


    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/updatePeronal")
    @ResponseBody
    internal fun updatePeronal(user: UserDO): R {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序")
        }
        return if (userService!!.updatePersonal(user) > 0) {
            R.ok()
        } else R.error()
    }


    @RequiresPermissions("sys:user:remove")
    @Log("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    internal fun remove(id: Long?): R {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序")
        }
        return if (userService!!.remove(id) > 0) {
            R.ok()
        } else R.error()
    }

    @RequiresPermissions("sys:user:batchRemove")
    @Log("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    internal fun batchRemove(@RequestParam("ids[]") userIds: Array<Long>): R {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序")
        }
        val r = userService!!.batchremove(userIds)
        return if (r > 0) {
            R.ok()
        } else R.error()
    }

    @PostMapping("/exit")
    @ResponseBody
    internal fun exit(@RequestParam params: Map<String, Any>): Boolean {
        // 存在，不通过，false
        return !userService!!.exit(params)
    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("请求更改用户密码")
    @GetMapping("/resetPwd/{id}")
    internal fun resetPwd(@PathVariable("id") userId: Long?, model: Model): String {

        val userDO = UserDO()
        userDO.userId = (userId)
        model.addAttribute("user", userDO)
        return "$prefix/reset_pwd"
    }

    @Log("提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    internal fun resetPwd(userVO: UserVO): R {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序")
        }
        try {
            userService!!.resetPwd(userVO, getUser())
            return R.ok()
        } catch (e: Exception) {
            return R.error(1, e.message!!)
        }

    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    internal fun adminResetPwd(userVO: UserVO): R {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序")
        }
        try {
            userService!!.adminResetPwd(userVO)
            return R.ok()
        } catch (e: Exception) {
            return R.error(1, e.message.toString())
        }

    }

    @GetMapping("/tree")
    @ResponseBody
    fun tree(): Tree<DeptDO> {
        var tree = Tree<DeptDO>()
        tree = userService!!.getTree()
        return tree
    }

    @GetMapping("/treeView")
    internal fun treeView(): String {
        return "$prefix/userTree"
    }

    @GetMapping("/personal")
    internal fun personal(model: Model): String {
        val userDO = userService!!.get(getUserId())
        model.addAttribute("user", userDO)
        model.addAttribute("hobbyList", dictService!!.getHobbyList(userDO))
        model.addAttribute("sexList", dictService!!.sexList)
        return "$prefix/personal"
    }

    @ResponseBody
    @PostMapping("/uploadImg")
    internal fun uploadImg(@RequestParam("avatar_file") file: MultipartFile, avatar_data: String, request: HttpServletRequest): R {
        if ("test" == getUsername()) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序")
        }
        var result: Map<String, Any>? = HashMap()
        try {
            result = userService!!.updatePersonalImg(file, avatar_data, getUserId())
        } catch (e: Exception) {
            return R.error("更新图像失败！")
        }

        return if (result != null && result!!.size > 0) {
            R.ok(result)
        } else {
            R.error("更新图像失败！")
        }
    }
}